import 'package:flutter/material.dart';
import 'package:flutter_pink_app/components/entrance_banner.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../composables/common_appbar.dart';
import '../composables/common_input.dart';
import '../composables/theme_button.dart';
import '../util.dart';
import '../route/delegate.dart';
import '../route/page.dart';
import '../business/login.dart';
import '../composables/popup_dialog.dart';

// 登陆页面
class BiliEntrancePage extends StatefulWidget {
  final bool tokenIsExpired;

  const BiliEntrancePage({Key key, this.tokenIsExpired}) : super(key: key);

  @override
  _BiliEntrancePageState createState() => _BiliEntrancePageState();
}

class _BiliEntrancePageState extends State<BiliEntrancePage> {
  bool _imageIsProtected = false; // 图片是否保护
  String _username = ''; // 用户名
  String _phone = ''; // 手机电话号码
  String _password = ''; // 密码
  bool _isLogin = false; // 是否登陆
  static const Map<int, String> _statusCodeMap = {
    5001: "确认，现在去注册~",
    5002: "确认，再检查一遍~"
  };
  bool get _buttonIsActive =>
      judgeMultStrIsNotEmpty(<String>[_password, _username, _phone]); // 按钮是否被激活

  @override
  void initState() {
    super.initState();
    if (widget.tokenIsExpired == true) {
      Fluttertoast.showToast(msg: "登陆使用的令牌已过期", gravity: ToastGravity.TOP);
    }
  }

  // 图片显示保护
  void _protectImage(bool value) {
    setState(() {
      _imageIsProtected = value;
    });
  }

  // 登陆函数
  Future<bool> _login(BuildContext ctx) async {
    // 锁
    if (_isLogin == true) {
      return false;
    }
    _isLogin = true;
    final res = await loginAccount(_username, _password);
    _isLogin = false; // 解锁
    // final info = res.data;
    // 规则校验
    if (_statusCodeMap.containsKey(res.statusCode)) {
      popupDialog(ctx,
          content: res.message, buttonText: _statusCodeMap[res.statusCode]);
      return false;
    }
    // // 规则校验
    // if(info is Map && _statusCodeMap.containsKey(info["code"])){
    //   popupDialog(ctx,content: info["msg"],buttonText: _statusCodeMap[info["code"]]);
    //   return false;
    // }
    // 未知错误时跳出
    if (res.statusCode != 0) {
      popupDialog(ctx, content: res.message, buttonText: "稍后再试"); // 请求失败逻辑
      return false;
    }
    // 登陆成功时处理跳转
    final delegate = BiliRouterDelegate.of(ctx);
    delegate.setNewRoutePath(BiliPageStatus('/main')); // 重新设置路径
    return true;
  }

  @override
  Widget build(BuildContext scaffoldContext) {
    return Scaffold(
      appBar: buildCommonAppbar(scaffoldContext,
          rightTextTrigger: () => BiliRouterDelegate.of(scaffoldContext)
              .push(BiliPageStatus('/regist')),
          needBackButton: false,
          rightText: '注册'),
      body: ListView(
        physics: const BouncingScrollPhysics(),
        children: <Widget>[
          EntranceBanner(_imageIsProtected),
          CommonInput(
            type: 'text',
            title: '用户名',
            placeholder: '请输入用户名',
            onChanged: (value) => setState(() => _username = value),
          ),
          CommonInput(
            type: 'number',
            title: '手机号',
            placeholder: '请输入手机号',
            onChanged: (value) => setState(() => _phone = value),
          ),
          CommonInput(
            type: 'password',
            title: '密码',
            placeholder: '请输入密码',
            onFocus: _protectImage,
            onChanged: (value) => setState(() => _password = value),
          ),
          Padding(
            padding: const EdgeInsets.all(15.0),
            child: ThemeActiveButton(
              '登  陆',
              isActive: _buttonIsActive,
              onPressed: () => _login(scaffoldContext),
            ),
          )
        ],
      ),
    );
  }
}
